﻿using System;
using System.Collections.Generic;
using System.Web;
using Wind.Utils;
using Wind.Comm;
using Wind.MultimediaStation.WebService.Entity;
using System.Xml;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Caching;

namespace Wind.MultimediaStation.WebService
{
    public class MultimediaStationNewsBusiness
    {

        public OMaterialInfo QueryByMaterialCode(OMaterialInfo info, string pageCode, int rowIndex)
        {
            try
            {
                string xmlText = GetFlexBlockInfoByCache(pageCode);
                XmlDocument oXML = new XmlDocument();
                oXML.LoadXml(xmlText);
                int iCount = oXML.ChildNodes[1].ChildNodes[0].ChildNodes.Count;
                if (iCount > 0)
                {
                    // Random ran = new Random((int)DateTime.Now.Ticks);
                    //int iResult = ran.Next(0, iCount);
                    XmlNode node;
                    if (rowIndex < iCount)
                    {
                        node = oXML.ChildNodes[1].ChildNodes[0].ChildNodes[rowIndex];
                        if (pageCode == "图片新闻")
                        {
                            string sHTML = GetHtmlContent(node.ChildNodes[1].InnerText);
                            info.MaterialName = GetPicturePath(sHTML);
                            info.MaterialValue = GetNews(sHTML);
                            if (info.MaterialValue.Length > 45)
                            {
                                info.MaterialValue = info.MaterialValue.Substring(0, 45) + "......";
                            }
                        }
                        else  //文字新闻
                        {
                            info.MaterialValue = node.ChildNodes[3].InnerText.Replace("【Wind金融屏】", "");
                            if (info.MaterialValue.Length > 20)
                            {
                                info.MaterialValue = info.MaterialValue.Substring(0, 20) + "......";
                            }
                        }
                        //if (pageCode == "ON0601")
                        //{
                        //    info.MaterialName = node.ChildNodes[2].InnerText;
                        //}
                    }
                    else
                    {
                        info.MaterialValue = "";
                    }
                    info.MaterialTime = DateTime.Now.ToString("yyyy-MM-dd HH:ss:mm");

                }
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationNewsBusiness QueryByMaterialCode Exception:", ex);
            }
            return info;
        }


        public string GetHtmlContent(string urls)
        {
            WebRequest wrq;
            HttpWebResponse wrp;

            wrq = HttpWebRequest.Create(urls);
            wrp = (HttpWebResponse)wrq.GetResponse();
            Stream resStream = wrp.GetResponseStream();
            StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
            string tempstr = sr.ReadToEnd();
            return tempstr;
        }

         string GetPicturePath(string sHTML)
        {
            Regex re = new Regex("<IMG id=newsimg.*src=.*>", RegexOptions.IgnoreCase);
            MatchCollection mc = re.Matches(sHTML);
            if (mc.Count > 0)
            {
                string sContent = mc[0].Groups[0].Value;

                return sContent.Substring(sContent.IndexOf("src=") + 5, sContent.IndexOf(">") - sContent.IndexOf("src=") - 6);
            }

            return string.Empty;

        }

         string GetNews(string sHTML)
        {
            Regex re = new Regex("<DIV id=news_content.*>", RegexOptions.IgnoreCase);
            MatchCollection mc = re.Matches(sHTML);
            if (mc.Count > 0)
            {
                string sContent = mc[0].Groups[0].Value;

                Regex reIn = new Regex("<p.*>", RegexOptions.IgnoreCase);
                MatchCollection mcIn = reIn.Matches(sHTML);
                string sContentIn = sContent.Remove(0, sContent.IndexOf(">") + 1);
                sContentIn = sContentIn.Remove(0, sContentIn.IndexOf(">") + 1);
                sContentIn = sContentIn.Substring(0, sContentIn.IndexOf("<"));
                if (sContentIn.Length > 50)
                {
                    return sContentIn.Substring(0, 50);
                }
                else
                {
                    return sContentIn;
                }

            }

            return string.Empty;

        }


        #region ---添加缓存----
        /// <summary>
        /// 获取 
        /// 
        /// </summary>
        private string GetFlexBlockInfoByCache(string pageCode)
        {

            string ck = pageCode;

            string sResult = null;

            if (HttpRuntime.Cache[ck] != null)
            {
                sResult = HttpRuntime.Cache[ck] as string;
            }

            if (sResult == null)
            {
                try
                {

                    uint appClass = 1411;
                    uint commandId = 6001;
                    string message = string.Format("calltype=cshap&name=livenewsnormal&param=tagcode:{0}&pagesize=20&pageno=1&xsltindex=1", pageCode);
                    object[] inputValues = new object[1];
                    object[] outputValues = null;
                    inputValues[0] = message;
                    CommandHeader cmdHeader = new CommandHeader(appClass, commandId);
                    RealProxy _Proxy = RealProxy.InitInstance();
                    bool expoRes = _Proxy.DoCommandProxy(cmdHeader, inputValues, out outputValues);
                    if (expoRes)
                    {
                        sResult = System.Text.Encoding.UTF8.GetString(outputValues[0] as byte[]);

                    }

                    int iCacheMinutes = 1;

                    if (sResult != null)
                    {
                        HttpRuntime.Cache.Add(ck, sResult, null, DateTime.Now.AddMinutes(iCacheMinutes), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, new CacheItemRemovedCallback(onRemoveCache_HTMLInfo));

                    }
                    else
                    {
                        // LogHelper.Write("MultimediaStationNewsBusiness.GetFlexBlockInfoByCache null");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Write("MultimediaStationNewsBusiness.GetFlexBlockInfoByCache Error: pageCode=" + pageCode +";" + ex.Message.ToString());
                    return string.Empty;
                }
            }
            return sResult;

        }

        private void onRemoveCache_HTMLInfo(string k, object v, System.Web.Caching.CacheItemRemovedReason r)
        {
            try
            {
                if (HttpRuntime.Cache[k] != null)
                {
                    HttpRuntime.Cache.Remove(k);

                }
                GetFlexBlockInfoByCache(k);
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationNewsBusiness.onRemoveCache_HTMLInfo error", ex);
            }
        }
        #endregion


    }

}
